package com.duolebo.uteped_sdk.service;

import static androidx.core.app.NotificationCompat.PRIORITY_HIGH;
import static androidx.core.app.NotificationCompat.VISIBILITY_PUBLIC;

import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.media.AudioAttributes;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.os.Vibrator;
import android.service.notification.NotificationListenerService;
import android.service.notification.StatusBarNotification;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.core.app.NotificationCompat;

import com.duolebo.uteped_sdk.R;
import com.duolebo.uteped_sdk.UTEPedBleClientHelper;
import com.duolebo.uteped_sdk.remind.MusicRemind;
import com.duolebo.uteped_sdk.remind.NotificationRemind;
import com.duolebo.uteped_sdk.utils.Const;
import com.duolebo.uteped_sdk.utils.DataSyncHelper;
import com.duolebo.uteped_sdk.utils.DeviceHelper;
import com.duolebo.uteped_sdk.utils.SPHelper;
import com.duolebo.uteped_sdk.utils.Tools;
import com.yc.nadalsdk.bean.FindMyPhoneNotify;
import com.yc.nadalsdk.bean.Notify;
import com.yc.nadalsdk.ble.open.UteBleDevice;
import com.yc.nadalsdk.constants.NotifyType;
import com.yc.nadalsdk.listener.DeviceNotifyListener;

import java.util.Timer;
import java.util.TimerTask;


/**
 * @Author: LiuYang
 * @Date: 2023/12/24 0:03
 * @Description:
 */
public class UTEPedNotificationService extends NotificationListenerService implements DeviceNotifyListener{
    private final static String TAG = "UTEPedNotification";
    private final static long SYNC_DATA_DELAY = 30 * 1000L;

    private long updatePeriod = Const.SYNC_PERIOD_DEFAULT;

    private Timer syncTimer;
    private Ringtone ringtone;

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(TAG, "onCreate");
        initNotify();
        toggleNotificationListenerService();
        Tools.setApplicationContext(this.getApplicationContext());
        UTEPedBleClientHelper.shareInstance().addDeviceNotifyListener(this);

        updatePeriod = SPHelper.shareInstance().getLong(Const.SYNC_PERIOD, Const.SYNC_PERIOD_DEFAULT);
        startSyncTimer();
    }

    @SuppressLint("UseCompatLoadingForDrawables")
    private void initNotify() {
        Log.d(TAG, "initNotify");
        String CHANNEL_ONE_ID = "1000";

        Intent nfIntent = new Intent();
        nfIntent.setAction("com.duolebo.share_fit.action.MAIN");
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, nfIntent, PendingIntent.FLAG_IMMUTABLE);
        @SuppressLint("WrongConstant") NotificationCompat.Builder builder = new NotificationCompat.Builder(this.getApplicationContext(), CHANNEL_ONE_ID)
                .setContentIntent(pendingIntent) // 设置PendingIntent
                .setSmallIcon(R.drawable.ic_notification_small) // 设置状态栏内的小图标
                //.setLargeIcon(bitmapIcon)// 设置大图标
                .setContentTitle(getResources().getString(R.string.app_name))
                .setContentText(getResources().getString(R.string.app_name)) // 设置上下文内容
                .setWhen(System.currentTimeMillis())// 设置该通知发生的时间
                .setVisibility(VISIBILITY_PUBLIC)// 锁屏显示全部通知
                //.setDefaults(Notification.DEFAULT_ALL)// //使用默认的声音、振动、闪光
                .setPriority(PRIORITY_HIGH);// 通知的优先级

        //----------------  新增代码 ------------------------
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            //修改安卓8.1以上系统报错
            NotificationChannel notificationChannel = new NotificationChannel(CHANNEL_ONE_ID, "app_service_notify", NotificationManager.IMPORTANCE_MIN);
            notificationChannel.enableLights(false);//如果使用中的设备支持通知灯，则说明此通知通道是否应显示灯
            notificationChannel.setShowBadge(false);//是否显示角标
            notificationChannel.enableVibration(false);//是否震动
            notificationChannel.setLockscreenVisibility(VISIBILITY_PUBLIC);//锁屏显示全部通知
            NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
            manager.createNotificationChannel(notificationChannel);
            builder.setChannelId(CHANNEL_ONE_ID);
        }
        Notification notification = builder.build(); // 获取构建好的Notification
        notification.defaults = Notification.DEFAULT_SOUND; //设置为默认的声音
        startForeground(1, notification);
    }

    @Override
    public void onNotificationPosted(StatusBarNotification sbn) {
        Log.d(TAG, "onNotificationPosted");
        Notification notification = sbn.getNotification();
        if (notification == null) {
            Log.e(TAG, "Notification is null, return");
            return;
        }

        MusicRemind.shareInstance().onNotificationPosted(sbn);
        NotificationRemind.shareInstance().onNotificationPosted(sbn);
    }


    @Override
    public void onNotificationRemoved(StatusBarNotification sbn) {
        Log.d(TAG, "onNotificationRemoved");

        if (sbn == null) {
            return;
        }

        Notification notification = sbn.getNotification();
        if (notification == null) {
            Log.e(TAG, "Notification is null, return");
        }
    }

    /**
     * 切换通知监听服务
     */
    private void toggleNotificationListenerService() {
        Log.d(TAG, "toggleNotificationListenerService");
        PackageManager pm = getPackageManager();
        pm.setComponentEnabledSetting(new ComponentName(this, UTEPedNotificationService.class), PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP);
        pm.setComponentEnabledSetting(new ComponentName(this, UTEPedNotificationService.class), PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(TAG, "onStartCommand");
        if (Tools.isNotificationListenerEnabled(this)) {
            Log.d(TAG, "notification listener not enabled");
            MusicRemind.shareInstance().init();
        }
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        cancelSyncTimer();
        Tools.release();
        super.onDestroy();
        stopForeground(true);
    }

    private void startSyncTimer() {
        syncTimer = new Timer();
        syncTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                if (DeviceHelper.getInstance().read(Const.M_setTimeSyncEnable, true)) {
                    UTEPedBleClientHelper.shareInstance().syncTime();
                }
                if (SPHelper.shareInstance().getBoolean(Const.M_setSyncDataEnable, false)) {
                    DataSyncHelper.getInstance().fetchDataAsync("");
                }
            }
        }, SYNC_DATA_DELAY, updatePeriod);
    }

    private void cancelSyncTimer() {
        if (syncTimer != null) {
            syncTimer.cancel();
            syncTimer = null;
        }
    }

    @Override
    public void onNotify(@NonNull UteBleDevice uteBleDevice, @NonNull Notify notify) {
        int eventType = notify.getType();
        switch (eventType) {
            case NotifyType.CAMERA_CONTROL:
                break;

            case NotifyType.FIND_MY_PHONE:
                FindMyPhoneNotify findMyPhoneNotify = (FindMyPhoneNotify) notify.getData();
                if (findMyPhoneNotify.getRingRequired()) {
                    startVibrate();
                    startRing();
                }
                else {
                    stopVibrate();
                    stopRing();
                }
                break;

            default:
        }
    }

    // 控制手机震动
    private void startVibrate() {
        Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
        vibrator.vibrate(5*1000);
    }

    private void stopVibrate() {
        try {
            Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
            vibrator.cancel();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 控制手机响铃
    private void startRing() {
        stopRing();
        try {
            Uri ringtoneUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALL);
            ringtone = RingtoneManager.getRingtone(getApplicationContext(), ringtoneUri);
            ringtone.play();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void stopRing() {
        if (ringtone != null) {
            ringtone.stop();
            ringtone = null;
        }
    }
}